import UserImformation.Account;

import javax.persistence.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/LoginCheckServlet")
public class LoginCheckServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String user_name = req.getParameter("user_name");
        String password = req.getParameter("password1");

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myDateBase");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        //判断该用户是否存在
        tx.begin();
        int exit = 0;

        String jpql = "select a from Account a where a.username = :username";
        Query query = em.createQuery(jpql);
        query.setParameter("username",user_name);
        List result = query.getResultList();

        if (result.size() != 0) {
            Account account = null;
            account = em.find(Account.class, user_name);
            System.out.println(result.size());
            if (account.getUsername().equals(user_name)) {
                if (account.getPassword().equals(password)) {
                    exit = 1;
                    Map<String, String> info = new HashMap<String, String>();
                    info.put("username", account.getUsername());
                    HttpSession session = req.getSession(true);
                    session.setAttribute("user", info);
                } else {
                    exit = 2;
                }
            }
            em.close();

            String json = "{\"exit\":\"" + exit + "\"}";
            resp.setContentType("application/json, charset = utf-8");
            resp.getWriter().println(json);
        }
    }
}